package com.study.talk.app.launcher;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import com.study.talk.R;

import java.util.Map;
import java.util.Set;

public class PermissionActivity extends AppCompatActivity {


    private AlertDialog dialog;
    private ActivityResultLauncher<String[]> permissionLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        dialog = new AlertDialog.Builder(getApplicationContext())
                .setTitle("提醒")
                .setMessage("拒绝授予权限将无法使用此应用哦！你确定退出嘛？")
                .setNegativeButton("确定", (dialogInterface, i) -> PermissionActivity.this.finish()).setPositiveButton("去授权", (dialogInterface, i) -> simpleSetting(PermissionActivity.this)).create();
        permissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
            if (result.isEmpty()) return;
            Boolean flag = false;
            Set<Map.Entry<String, Boolean>> set = result.entrySet();
            for (Map.Entry<String, Boolean> item : set) {
                flag = item.getValue();
                if (!item.getValue()) {
                    Log.e("err", "onActivityResult: " + item.getKey());
                }
            }
            if (flag) {
                toStart();
            } else {
                showDialog();
            }
        });
        checkPermission();
    }

    public void toStart() {
        startActivity(new Intent(PermissionActivity.this, StartActivity.class));
        finish();
    }

    private void showDialog() {
        if (!dialog.isShowing()) {
            dialog.show();
            dialog.setCanceledOnTouchOutside(false);
        }
    }

    private void checkPermission() {
        boolean flag = true;
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            permissions = new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.POST_NOTIFICATIONS,
                    Manifest.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING
            };
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(PermissionActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
        } else {
            permissions = new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.ACCESS_FINE_LOCATION,
            };
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(PermissionActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
        }
        if (flag) toStart();
        else permissionLauncher.launch(permissions);

    }

    public void simpleSetting(Context context) {
        Intent intent = new Intent();
        try {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // 将用户引导到系统设置页面
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
            context.startActivity(intent);
        } catch (Exception e) {//抛出异常就直接打开设置页面
            intent = new Intent(Settings.ACTION_SETTINGS);
            context.startActivity(intent);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!dialog.isShowing()) {
            checkPermission();
        }
    }


    // 跳转至设置页面，让用户手动开启允许管理所有文件
    public void setting(Activity activity) {
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent(
                    Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + activity.getPackageName()));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
        }
    }

    // 跳转系统设置-悬浮窗页面
    public void alertWindowsPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}